<template>
  <div>
    <div class="pagebg sh"></div>
    <div class="container">
      <h1 class="t_nav">
        <span>慢生活，不是懒惰，放慢速度不是拖延时间，而是让我们在生活中寻找到平衡。</span>
        <a href="/" class="n1">网站首页</a>
        <a href="/" class="n2">搜索</a>
      </h1>

      <!--blogsbox begin-->
      <div class="blogsbox">
        <div v-for="item in blogData" :key="item.uid" class="blogs" data-scroll-reveal="enter bottom over 1s">
          <div style="display: flex;">
            <div class="author">
              <span class="iconfont">&#xe60f;</span>
              <a href="javascript:void(0);" @click="goToAuthor(item.author)">{{item.author}}</a>
            </div>
            <div class="createTime">
              <span class="iconfont">&#xe606;</span>
              {{item.createTime}}
            </div>
          </div>

          <h3 class="blogtitle">
            <a href="javascript:void(0);" @click="goToInfo(item)">{{item.title}}</a>
          </h3>

          <p class="blogtext">{{item.summary}}</p>

          <span class="blogpic">
            <img v-for="(photo, index) in item.photoList" :key="index" :src="photo" alt="" />
          </span>


          <div class="bloginfo">
            <ul>
              <li class="lmname" v-if="item.blogSort">
                <span class="iconfont">&#xe603;</span>
                <a href="javascript:void(0);" @click="goToList(item.blogSort.uid)">{{item.blogSort.sortName}}</a>
              </li>
              <li class="view">
                <span class="iconfont">&#xe8c7;</span>
                <span>{{item.clickCount}}</span>
              </li>
              <li class="like">
                <span class="iconfont">&#xe663;</span>
                {{item.collectCount}}
              </li>
            </ul>
          </div>
        </div>

        <div class="isEnd">
          <div class="loadContent" @click="loadContent" v-if="!isEnd && !loading && totalPages>0">点击加载更多</div>

          <div class="lds-css ng-scope" v-if="!isEnd && loading">
            <div style="width:100%;height:100%" class="lds-facebook">
              <div></div>
              <div></div>
              <div></div>
            </div>
          </div>

          <span v-if="blogData.length >= 0 && isEnd &&!loading && totalPages>0">我也是有底线的~</span>

          <span v-if="totalPages == 0 && !loading">空空如也~</span>
        </div>
      </div>
      <!--blogsbox end-->

      <div class="sidebar">
        <TagCloud :hotTagData="hotTagData"></TagCloud>
      </div>
    </div>
  </div>
</template>

<script>
  import TagCloud from "../components/TagCloud";
  import HotBlog from "../components/HotBlog";
  import {
    getHotTag
  } from "../api/index";
  import {
    searchBlog,
    searchBlogByES,
    searchBloBySolr,
    searchBlogByTag,
    searchBlogBySort,
    searchBlogByAuthor
  } from "../api/search";
  import {
    getBlogByUid
  } from "../api/blogContent";

  export default {
    name: "list",
    data() {
      return {
        hotTagData: [], //最新标签
        searchModel: 0, //搜索模式 0:SQL搜索、1:ES搜索、2:Solr搜索
        blogData: [],
        keywords: "",
        currentPage: 1,
        totalPages: 0,
        pageSize: 10,
        total: 0, //总数量
        tagUid: "",
        searchBlogData: [], //搜索出来的文章
        sortUid: "",
        isEnd: false, //是否到底底部了
        loading: false //内容是否正在加载
      };
    },
    components: {
      TagCloud,
      HotBlog,
    },
    created() {
      this.keywords = this.$route.query.keyword;
      this.tagUid = this.$route.query.tagUid;
      this.sortUid = this.$route.query.sortUid;
      this.author = this.$route.query.author;
      let model = this.$route.query.model;
      if (model) {
        this.searchModel = model
      }
      getHotTag().then(response => {
        if (response.code === this.$ECode.SUCCESS) {
          this.hotTagData = response.data;
        }
      });
      if (
        this.keywords == undefined &&
        this.tagUid == undefined &&
        this.sortUid == undefined &&
        this.author == undefined
      ) {
        return;
      }

      this.search();
    },
    mounted() {
      const sidebar = this.$el.querySelector('.sidebar');
      this.stickyOffset = sidebar.offsetTop; // 获取 .sidebar 元素距离顶部的距离

      window.addEventListener('resize', this.updateFixedPosition);

      // 添加滚动事件监听器
      window.addEventListener('scroll', this.handleScroll);
      // 注册scroll事件并监听
      // var that = this;
      // window.addEventListener("scroll", function() {
      //   let scrollTop = document.documentElement.scrollTop; //当前的的位置
      //   let scrollHeight = document.documentElement.scrollHeight; //最高的位置
      //   if (scrollTop >= 0.6 * scrollHeight && !that.isEnd && !that.loading) {
      //     that.loading = true;
      //     that.currentPage = that.currentPage + 1;
      //     that.search();
      //   }
      // });
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.updateFixedPosition);
      // 在组件销毁前移除滚动监听
      window.removeEventListener('scroll', this.handleScroll);
    },
    watch: {
      $route(to, from) {
        this.keywords = this.$route.query.keyword;
        this.tagUid = this.$route.query.tagUid;
        this.sortUid = this.$route.query.sortUid;
        this.searchBlogData = [] // 清空查询出来的博客
        this.search();
      }
    },
    methods: {
      //跳转到文章详情
      goToInfo(blog) {
        if (blog.type == "0") {
          let routeData = this.$router.resolve({
            path: "/info",
            query: {
              blogOid: blog.oid
            }
          });
          window.open(routeData.href, '_blank');
        } else if (blog.type == "1") {
          var params = new URLSearchParams();
          params.append("uid", blog.uid);
          getBlogByUid(params).then(response => {
            // 记录一下用户点击日志
          });
          window.open(blog.outsideLink, '_blank');
        }
      },
      //点击了分类
      goToList(uid) {
        let routeData = this.$router.resolve({
          path: "/list",
          query: {
            sortUid: uid
          }
        });
        window.open(routeData.href, '_blank');
      },
      goToAuthor(author) {
        let routeData = this.$router.resolve({
          path: "/list",
          query: {
            author: author
          }
        });
        window.open(routeData.href, '_blank');
      },
      // 加载内容
      loadContent: function() {
        this.currentPage = this.currentPage + 1;
        this.search();
      },
      convertSearchData: function(that, response) {
        if (response.code == this.$ECode.SUCCESS) {
          that.isEnd = false;
          //获取总页数
          that.totalPages = response.data.blogList.length;
          that.total = response.data.total;
          that.pageSize = response.data.pageSize;
          that.currentPage = response.data.currentPage;
          var blogData = response.data.blogList;

          // 判断搜索的博客是否有内容
          if (response.data.total <= 0) {
            that.isEnd = true;
            that.loading = false;
            this.blogData = []
            return;
          }
          //全部加载完毕
          if (blogData.length < that.pageSize) {
            that.isEnd = true;
          }
          blogData = that.searchBlogData.concat(blogData);
          that.searchBlogData = blogData;
          this.blogData = blogData;
        } else {
          that.isEnd = true;
        }
        that.loading = false;
      },
      updateFixedPosition() {
        const fixedElement = this.$el.querySelector('.fixed');
        const blogsBox = this.$el.querySelector('.blogsbox');

        if (fixedElement && blogsBox) {
          const viewportWidth = window.innerWidth;
          const blogsBoxRect = blogsBox.getBoundingClientRect();
          const blogsBoxRight = viewportWidth - blogsBoxRect.right;

          fixedElement.style.right = blogsBoxRight - 397 + 'px';
        }
      },
      handleScroll() {
        // console.log(window.pageYOffset)
        // console.log(sticky)
        const sidebar = this.$el.querySelector('.sidebar');
        if (window.pageYOffset >= this.stickyOffset) {
          sidebar.classList.add('fixed');
          this.updateFixedPosition()
        } else {
          sidebar.classList.remove('fixed');
        }
        const documentHeight = document.documentElement.scrollHeight;
        // 获取当前滚动位置
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        // 获取视口高度
        const windowHeight = window.innerHeight || document.documentElement.clientHeight;
        // 计算距离底部的距离
        const distanceFromBottom = documentHeight - (scrollTop + windowHeight);
        // console.log(distanceFromBottom)
        let value = 203;
        if (distanceFromBottom <= value) {
          sidebar.style.top = distanceFromBottom - value + 'px'
        } else {
          sidebar.style.top = '0px'
        }
      },
      search: function() {
        let searchModel = this.searchModel
        let that = this;
        that.loading = true;
        if (this.keywords != undefined) {
          let params = new URLSearchParams();
          params.append("currentPage", that.currentPage);
          params.append("pageSize", that.pageSize);
          params.append("keywords", that.keywords);

          if (searchModel == 0) {
            searchBlog(params).then(response => {
              that.convertSearchData(that, response)
            });
          } else if (searchModel == 1) {
            searchBlogByES(params).then(response => {
              that.convertSearchData(that, response)
            });
          } else if (searchModel == 2) {
            searchBlogByES(params).then(response => {
              that.convertSearchData(that, response)
            });
          }
        } else if (this.tagUid != undefined) {
          var params = new URLSearchParams();

          params.append("tagUid", that.tagUid);
          params.append("currentPage", that.currentPage);
          params.append("pageSize", that.pageSize);

          searchBlogByTag(params).then(response => {
            if (response.code == this.$ECode.SUCCESS && response.data.records.length > 0) {
              that.isEnd = false;
              //获取总页数
              that.totalPages = response.data.total;

              var blogData = response.data.records;
              that.total = response.data.total;
              that.pageSize = response.data.size;
              that.currentPage = response.data.current;

              //全部加载完毕
              if (blogData.length < that.pageSize) {
                that.isEnd = true;
              }

              // 设置分类名
              for (var i = 0; i < blogData.length; i++) {
                blogData[i].blogSort = blogData[i].blogSort.sortName;
              }

              blogData = that.searchBlogData.concat(blogData);
              that.searchBlogData = blogData;
              this.blogData = blogData;
              that.loading = false;

            } else {

              that.isEnd = true;
              that.loading = false;
            }
          });
        } else if (this.sortUid != undefined) {
          var params = new URLSearchParams();

          params.append("blogSortUid", that.sortUid);
          params.append("currentPage", that.currentPage);
          params.append("pageSize", that.pageSize);

          searchBlogBySort(params).then(response => {
            if (response.code == this.$ECode.SUCCESS && response.data.records.length > 0) {
              that.isEnd = false;
              //获取总页数
              that.totalPages = response.data.total;

              var blogData = response.data.records;
              that.total = response.data.total;
              that.pageSize = response.data.size;
              that.currentPage = response.data.current;

              //全部加载完毕
              if (blogData.length < that.pageSize) {
                that.isEnd = true;
              }

              for (var i = 0; i < blogData.length; i++) {
                blogData[i].blogSort = blogData[i].blogSort.sortName;
              }

              blogData = that.searchBlogData.concat(blogData);
              that.searchBlogData = blogData;
              this.blogData = blogData;
              that.loading = false;
            } else {


              that.isEnd = true;
              that.loading = false;
            }
          });
        } else if (this.author != undefined) {
          var params = new URLSearchParams();
          params.append("author", that.author);
          params.append("currentPage", that.currentPage);
          params.append("pageSize", that.pageSize);
          searchBlogByAuthor(params).then(response => {
            if (response.code == this.$ECode.SUCCESS && response.data.records.length > 0) {
              that.loading = false;

              that.isEnd = false;

              //获取总页数
              that.totalPages = response.data.total;

              var blogData = response.data.records;
              that.total = response.data.total;
              that.pageSize = response.data.size;
              that.currentPage = response.data.current;

              //全部加载完毕
              if (blogData.length < that.pageSize) {
                that.isEnd = true;
              }

              for (var i = 0; i < blogData.length; i++) {
                if (blogData[i].blogSort == undefined) {
                  blogData[i].blogSort = "未分类";
                } else {
                  blogData[i].blogSort = blogData[i].blogSort.sortName;
                }
              }

              blogData = that.searchBlogData.concat(blogData);
              that.searchBlogData = blogData;
              this.blogData = blogData;
              that.loading = false;
            } else {

              that.isEnd = true;
              that.loading = false;
            }
          });
        }
      }
    }
  };
</script>

<style scoped>
  /* 博客信息 */
  .bloginfo {
    position: absolute;
    bottom: 16px;
    left: 16px;
    width: calc(100% - 32px);
    overflow: hidden;
    font-size: 12px;
    margin-top: 0;
    width: 100%;
    clear: both;
  }

  /* 博客信息列表 */
  .bloginfo ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  /* 博客信息列表项 */
  .bloginfo ul li {
    float: left;
    padding: 0 10px;
    color: #748594;
    line-height: 1.5;
    display: inline-block;
  }

  /* 博客信息列表项链接 */
  .bloginfo ul li a {
    color: #748594;
  }

  /* 链接悬停效果 */
  .bloginfo ul li a:hover {
    color: #000;
  }

  .bloginfo ul li {
    background-image: none
  }

  .bloginfo .createTime {
    display: none
  }

  .bloginfo ul li {
    margin-right: 5px
  }


  .isEnd {
    float: left;
    width: 100%;
    height: 80px;
    text-align: center;
  }

  .ng-scope {
    margin: 0 auto;
    width: 18%;
    height: 10%;
  }



  @keyframes lds-facebook_1 {
    0% {
      top: 0px;
      height: 200px;
    }

    50% {
      top: 80px;
      height: 40px;
    }

    100% {
      top: 80px;
      height: 40px;
    }
  }

  @-webkit-keyframes lds-facebook_1 {
    0% {
      top: 0px;
      height: 200px;
    }

    50% {
      top: 80px;
      height: 40px;
    }

    100% {
      top: 80px;
      height: 40px;
    }
  }

  @keyframes lds-facebook_2 {
    0% {
      top: 20px;
      height: 160px;
    }

    50% {
      top: 80px;
      height: 40px;
    }

    100% {
      top: 80px;
      height: 40px;
    }
  }

  @-webkit-keyframes lds-facebook_2 {
    0% {
      top: 20px;
      height: 160px;
    }

    50% {
      top: 80px;
      height: 40px;
    }

    100% {
      top: 80px;
      height: 40px;
    }
  }

  @keyframes lds-facebook_3 {
    0% {
      top: 40px;
      height: 120px;
    }

    50% {
      top: 80px;
      height: 40px;
    }

    100% {
      top: 80px;
      height: 40px;
    }
  }

  @-webkit-keyframes lds-facebook_3 {
    0% {
      top: 40px;
      height: 120px;
    }

    50% {
      top: 80px;
      height: 40px;
    }

    100% {
      top: 80px;
      height: 40px;
    }
  }

  .lds-facebook {
    position: relative;
  }

  .lds-facebook div {
    position: absolute;
    width: 20px;
  }

  .lds-facebook div:nth-child(1) {
    left: 40px;
    background: #1d0e0b;
    -webkit-animation: lds-facebook_1 1s cubic-bezier(0, 0.5, 0.5, 1) infinite;
    animation: lds-facebook_1 1s cubic-bezier(0, 0.5, 0.5, 1) infinite;
    -webkit-animation-delay: -0.2s;
    animation-delay: -0.2s;
  }

  .lds-facebook div:nth-child(2) {
    left: 90px;
    background: #774023;
    -webkit-animation: lds-facebook_2 1s cubic-bezier(0, 0.5, 0.5, 1) infinite;
    animation: lds-facebook_2 1s cubic-bezier(0, 0.5, 0.5, 1) infinite;
    -webkit-animation-delay: -0.1s;
    animation-delay: -0.1s;
  }

  .lds-facebook div:nth-child(3) {
    left: 140px;
    background: #d88c51;
    -webkit-animation: lds-facebook_3 1s cubic-bezier(0, 0.5, 0.5, 1) infinite;
    animation: lds-facebook_3 1s cubic-bezier(0, 0.5, 0.5, 1) infinite;
  }

  .lds-facebook {
    width: 90px !important;
    height: 90px !important;
    -webkit-transform: translate(-45px, -45px) scale(0.45) translate(45px, 45px);
    transform: translate(-45px, -45px) scale(0.45) translate(45px, 45px);
  }
</style>
